package com.isky.visual.util;

import org.apache.commons.codec.binary.Hex;
import org.apache.commons.lang3.StringUtils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;

public class MD5Util {
    /**
     * 普通MD5
     */
    public static String MD5(String input) {
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            return "check jdk";
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
        char[] charArray = input.toCharArray();
        byte[] byteArray = new byte[charArray.length];

        for (int i = 0; i < charArray.length; i++) {
            byteArray[i] = (byte) charArray[i];
        }
        byte[] md5Bytes = md5.digest(byteArray);
        StringBuffer hexValue = new StringBuffer();
        for (int i = 0; i < md5Bytes.length; i++) {
            int val = ((int) md5Bytes[i]) & 0xff;
            if (val < 16) {
                hexValue.append("0");
            }
            hexValue.append(Integer.toHexString(val));
        }
        return hexValue.toString();

    }

    /**
     * 加盐MD5
     */
    public static String generateMD5(String password) {
        Random r = new Random();
        StringBuilder sb = new StringBuilder(16);
        sb.append(r.nextInt(99999999)).append(r.nextInt(99999999));
        int len = sb.length();
        if (len < 16) {
            for (int i = 0; i < 16 - len; i++) {
                sb.append("0");
            }
        }
        String salt = sb.toString();
        password = md5Hex(md5Hex(password + salt));
        char[] cs = new char[48];
        for (int i = 0; i < 48; i += 3) {
            cs[i] = password.charAt(i / 3 * 2);
            char c = salt.charAt(i / 3);
            cs[i + 1] = c;
            cs[i + 2] = password.charAt(i / 3 * 2 + 1);
        }
        return new String(cs);
    }

    /**
     * 校验加盐后是否和原文一致
     */
    public static boolean verify(String password, String md5) {
        if (StringUtils.isEmpty(md5)) {
            return false;
        }
        char[] cs1 = new char[32];
        char[] cs2 = new char[16];
        for (int i = 0; i < 48; i += 3) {
            cs1[i / 3 * 2] = md5.charAt(i);
            cs1[i / 3 * 2 + 1] = md5.charAt(i + 2);
            cs2[i / 3] = md5.charAt(i + 1);
        }
        String salt = new String(cs2);
        return md5Hex(md5Hex(password + salt)).equals(new String(cs1));
    }

    /**
     * 获取十六进制字符串形式的MD5摘要
     */
    private static String md5Hex(String src) {
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            byte[] bs = md5.digest(src.getBytes());
            return new String(new Hex().encode(bs));
        } catch (Exception e) {
            return null;
        }
    }

    public static String decodeMD5(String inStr) {
        String result = convertMD5(inStr);
        result = convertMD5(result);
        return result;
    }

    /**
     * 加密解密算法 执行一次加密，两次解密
     */
    public static String convertMD5(String inStr) {

        char[] a = inStr.toCharArray();
        for (int i = 0; i < a.length; i++) {
            a[i] = (char) (a[i] ^ 't');
        }
        String s = new String(a);

        return s;

    }


    // 测试主函数
    public static void main(String args[]) {
        // 原文
        String plaintext = "123456";

        // 1、
        System.out.println("原始：" + plaintext);
        System.out.println("普通MD5后：" + MD5Util.MD5(plaintext));
        System.out.println("普通MD5解密后：" + decodeMD5(plaintext));

        // 2、获取加盐后的MD5值
//		String ciphertext = MD5Util.generateMD5(plaintext);// 密码保存到数据库
//		System.out.println("加盐后MD5：" + ciphertext);
//		System.out.println("是否是同一字符串:" + MD5Util.verify(plaintext, ciphertext));

//		/**
//		 * 其中某次asoTest字符串的两次加盐MD5值
//		 */
//		String[] tempSalt = { "63010d016d2d950341f74951167a4d64e43a055867887826",
//				"83616191ee7be4655324268286ea13033187365d07e09542",
//				"a60f9d363087a0705194f18b668f75d99e2eb1794719e81f" };
//
//		for (String temp : tempSalt) {
//			System.out.println("是否是同一字符串:" + MD5Util.verify(plaintext, temp));
//		}

//		System.out.println(MD5Util.generateMD5("021423"));
//		System.out.println("xxxxxxxxxxxxx=" + MD5Util.verify("021423", "a3f51b92be52f2c22493383b38fc06f47e3b277713172f19"));

//		String regex = "^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,16}$";
//		String str = "a1aaaaaaaaaaaaaaa";
//		System.out.println(str.matches(regex));


    }
}
